package me.zhengjie.modules.system.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.inspection.domain.InspectionItem;
import me.zhengjie.modules.inspection.service.InspectionItemService;
import me.zhengjie.modules.inspection.service.dto.InspectionItemDTO;
import me.zhengjie.modules.inspection.service.dto.InspectionItemQueryCriteria;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria;
import me.zhengjie.utils.HttpResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
* @author Zheng Jie
* @date 2019-04-10
*/
@RestController
@RequestMapping("api")
public class DictDetailController {

    @Autowired
    private DictDetailService dictDetailService;
    @Autowired
    private InspectionItemService inspectionItemService;

    private static final String ENTITY_NAME = "dictDetail";

    @Log("查询字典详情")
    @GetMapping(value = "/dictDetail")
    public ResponseEntity getDictDetails(DictDetailQueryCriteria criteria,
                                         @PageableDefault(value = 10, sort = {"sort"}, direction = Sort.Direction.ASC) Pageable pageable){
        return new ResponseEntity(dictDetailService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @Log("新增字典详情")
    @PostMapping(value = "/dictDetail")
    //@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_CREATE')")
    public ResponseEntity create(@Validated @RequestBody DictDetail resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        List<DictDetail> list = dictDetailService.findByLabelOrValue(resources.getDict().getId(), resources.getLabel(), resources.getValue()) ;
        for(DictDetail detail:list ) {
            if(detail.getDict().getId().equals(resources.getDict().getId())) {
                if (detail.getLabel().equals(resources.getLabel())) {
                    throw new BadRequestException(String.format("%s已经存在", resources.getLabel()));
                }
                if (detail.getValue().equals(resources.getValue())) {
                    throw new BadRequestException(String.format("字典值%s已经存在", resources.getValue()));
                }
            }
        }
        return new ResponseEntity(dictDetailService.create(resources),HttpStatus.CREATED);
    }

    @Log("修改字典详情")
    @PutMapping(value = "/dictDetail")
    //@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_EDIT')")
    public ResponseEntity update(@Validated(DictDetail.Update.class) @RequestBody DictDetail resources){
        dictDetailService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("删除字典详情")
    @DeleteMapping(value = "/dictDetail/{id}")
    //@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_DELETE')")
    public ResponseEntity delete(@PathVariable Long id){
        try {
            dictDetailService.delete(id);
            return new ResponseEntity(HttpStatus.OK);
        }catch(Exception ex) {
            ex.printStackTrace();
            return  HttpResponseUtils.passDefaultResponse(ex);
        }
    }

    @Log("根据name查询字典")
    @GetMapping(value = "/dictDetail/findByDeptId/{id}")
    //@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_SELECT')")
    public ResponseEntity getDictsByNmae(@PathVariable int  id){

        return new ResponseEntity(dictDetailService.findByDeptId(id), HttpStatus.OK);
    }

    @Log("构建巡检项目树形结构")
    @GetMapping(value = "/dictDetail/inspectiontree")
    public ResponseEntity getInspectionTree() {
        List<Long> ids = new ArrayList<Long>();
        ids.add(6L);
        ids.add(24L);
        ids.add(28L);

        DictDetailQueryCriteria criteria = new DictDetailQueryCriteria();
        criteria.setDictId(ids);

        List<DictDetail> details = dictDetailService.queryAll(criteria);  //获取巡检对象
        List<InspectionItemDTO> items = (List<InspectionItemDTO>)inspectionItemService.queryAll(new InspectionItemQueryCriteria()); //全部项目

        //项目hash
        HashMap<Long, JSONArray> types = new HashMap<>();
        for(InspectionItemDTO item: items) {
            JSONObject obj = new JSONObject();
            obj.put("id", item.getId());
            obj.put("label", item.getItemname());

            Long detailId = item.getObjid() ;
            JSONArray array = types.getOrDefault(detailId, new JSONArray());
            array.add(obj);
            types.put(detailId,array);
        }

        //类型
        HashMap<Long, JSONArray> inspections = new HashMap<>();
        for(DictDetail detail: details) {
            JSONObject obj = new JSONObject();
            obj.put("id", detail.getId());
            obj.put("label", detail.getLabel());
            JSONArray children = types.getOrDefault(detail.getId(), new JSONArray());
            obj.put("children", children);

            Long dictId = detail.getDict().getId();
            JSONArray array = inspections.getOrDefault(dictId, new JSONArray());
            array.add(obj);
            inspections.put(dictId, array);
        }

        JSONArray result = new JSONArray();
        {
            JSONObject item1 = new JSONObject();
            item1.put("id", 6);
            item1.put("label", "设备类巡检");
            item1.put("children", inspections.getOrDefault(6L, new JSONArray()));
            result.add(item1);
        }
        {
            JSONObject item2 = new JSONObject();
            item2.put("id", 24L);
            item2.put("label", "设施类巡检");
            item2.put("children", inspections.getOrDefault(24L, new JSONArray()));
            result.add(item2);
        }
        {
            JSONObject item3 = new JSONObject();
            item3.put("id", 28L);
            item3.put("label", "管理类巡检");
            item3.put("children", inspections.getOrDefault(28L, new JSONArray()));
            result.add(item3);
        }
        return new ResponseEntity(result, HttpStatus.OK);
     }
}